from django.shortcuts import render
from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework.response import Response
from django.core.paginator import Paginator
from django.db.models import Max,Q,F,Min,Avg,Count,Sum
from django.contrib.auth.hashers import make_password,check_password
import datetime  #导入时间包
import time
import random
from .ser import *
from django.http import HttpResponse
from meiduo01.models import *

# Create your views here.

from utils.comm import xTree

class Home(APIView):
    def get(self,request):
        # 获取全部数据
        datas = Category.objects.all()
        # 调用序列化器
        ser = HomeSer(datas,many=True).data
        #
        list = xTree(ser)
        return Response({"code":200,"list":list,})


# 读取首页三级分类
class Home1(APIView):
    def get(self, request):
        # 读取一级
        cates = Category.objects.filter(parent_id__isnull=True).all()
        # 查询一级分类，一级下面的二级，一级下面的三级，一级下面所有的商品
        categoods = []
        for j in cates:
            dict = {}
            dict['id'] = j.id
            dict['name'] = j.name
            dict['pic'] = str(j.pic)
            two = j.subs.all()
            twoser = HomeSer(two, many=True)
            dict['two'] = twoser.data
            # 获取三级
            three = Category.objects.filter(top_parent=j.id, level=3).all()
            threeser = HomeSer(three, many=True)
            dict['three'] = threeser.data
            # 获取商品,排序，新品按时间倒序排，价格，销量
            sorted = request.GET.get('sorted')
            topid = request.GET.get('topid')

            goods = Goods.objects.filter(category1_id=j.id, home_show=1).all()
            if sorted:
                if int(topid) == int(j.id):
                    goods = Goods.objects.filter(category1_id=j.id, home_show=1).order_by('-' + sorted).all()

            gser = GoodsSer(goods, many=True)
            dict['goods'] = gser.data
            categoods.append(dict)
        return Response({"code": 200, 'categoods': categoods})
#读取首页三级分类
# class Home(APIView):
#     def get(self,request):
#         #读取一级
#         cates = Category.objects.filter(parent_id__isnull=True).all()
#         list=[]
#         for i in cates:
#             dict={}
#             dict['id'] = i.id
#             dict['name'] = i.name
#             #读取二级
#             two = i.subs.all()
#             print(two)
#             twolist=[]
#             #遍历二级获取三级
#             for j in two:
#                 twodict={}
#                 twodict['id'] = j.id
#                 twodict['name'] = j.name
#                 three = j.subs.all()
#                 ser = CateSer(three,many=True)
#                 twodict['subs'] = ser.data
#                 twolist.append(twodict)
#
#             dict['subs'] = twolist
#             list.append(dict)
#         return Response({"code":200,'catelist':list})

# 商品详情页面
class Getgoods(APIView):
    def get(self,request):
        id = request.GET.get("id")
        print(id)
        goods = Goods.objects.filter(id=id).first()
        ser = GoodsSer(goods)
        return Response({"code":200,"list":ser.data})
# 添加购物车
class CartM(APIView):
    def post(self,request):
        #判断用户是否购买过此商品
        userid = request.data.get('user')
        goodsid = request.data.get('goods')
        number = request.data.get('number')
        cart = Cart.objects.filter(user_id=userid,goods=goodsid).first()
        if cart:
            #买过数量+
            cart.number += number
            cart.save()
            return Response({"code":200})
        else:
            #没买过购物车新增一条记录
            ser = CareSer(data=request.data)
            if ser.is_valid():
                ser.save()
                return Response({"code":200})
            else:
                print(ser.errors)
                return Response({"code":2000})
            # redis 添加
            # class AddViewHistory(APIView):
            #     def post(self, request):
            #         userid = request.data.get('userid')
            #         goodsid = request.data.get('goodsid')
            #         key = 'history_%userid' % int(userid)
            #         conn = get_redis()
            #         # 先去重
            #         conn.lrem(key, 0, goodsid)
            #         # 添加
            #         conn.lpush(key, goodsid)
            #         # 截取
            #         data = conn.ltrim(key, 0, 1)
            #
            #         history = conn.lrange(key, 0, -1)
            #         list = []
            #         for i in history:
            #             goods = Goods.objects.filter(id=i).first()
            #             ser = GoodsSer(goods)
            #             list.append(ser.data)
            #         return Response({'code': 200, 'list': list})
    def get(self,request):
        userid = request.GET.get('userid')
        cart = Cart.objects.filter(user_id=userid).all()
        ser = ShowcareSer(cart,many=True)
        # 全选
        selected_all = True
        total = 0
        select_total = 0
        select_money = 0
        for i in cart:
            total +=i.number
            if i.is_checked == False:
                selected_all = False
            else:
                select_total +=i.number
                goods = Goods.objects.filter(id=i.goods_id).first()
                select_money +=i.number * float(goods.price)
        return Response({'code':200,"list":ser.data,'selected_all':selected_all,'total':total,
                         'select_total':select_total,'select_money':select_money})

    def put(self,request):
        id=request.GET.get("id")
        cart = Cart.objects.filter(id=id).first()
        if cart.is_checked == True:
            cart.is_checked = False
        else:
            cart.is_checked = True
        cart.save()
        return Response({"code":200})


class SelectAll(APIView):
    def put(self,request):
        userid = request.GET.get('userid')
        selected_all = request.GET.get('selected_all')
        if selected_all == 'true':
            Cart.objects.filter(user_id=userid).update(is_checked = True)
        else:
            Cart.objects.filter(user_id=userid).update(is_checked=False)
        return Response({'code': 200})
    def post(self,request):
        id = request.data.get('id')
        type = request.data.get('type')
        count = request.data.get('count')
        cart = Cart.objects.filter(id=id).first()
        if type==1:
            #加
            cart.number +=1
        elif type == 2:
            #减
         #判断实录是否>1
            if cart.number>1:
                cart.number -= 1
        else:
            #数量更新
            cart.number = int(count)
        cart.save()
        return Response({"code":200})
class GetgoodslistM(APIView):
    def get(self,request):
        #获取用户id
        userid = request.GET.get("userid")
        cartlist = Cart.objects.filter(user_id=userid,is_checked=True).all()
        ser = ShowcareSer(cartlist,many=True)
        total = 0
        tmoney= 0
        for i in ser.data:
            #查询总数量
            total += i['number']
            #查询总价格
            tmoney += i['number'] * float(i['goods']['price'])
        return Response({"code":200,"list":ser.data,'total':total,'tmoney':tmoney})


import datetime
import random
from meiduo01.ser import ShowAddressManageSer
from django.db import transaction
class Createorders(APIView):
    @transaction.atomic()
    def post(self,request):
        #获取userid
        userid = request.data.get("userid")
        pay_method = request.data.get("pay_method")
        address_id = request.data.get("address_id")
        #根据userid查询购物车选中记录
        cart = Cart.objects.filter(user_id=userid,is_checked=True).all()
        careser = ShowcareSer(cart,many=True)
        #遍历购物车
        total_amount = 0
        for i in careser.data:
            total_amount += i['number'] * float(i['goods']['price'])
        #生成订单号
        #查找地址构造地址信息
        #订单号
        order_no = datetime.datetime.strftime(datetime.datetime.now(), '%Y%M%D%H%M%S') + str(userid) + str(random.randint(1000, 9999))
        #地址信息
        # 查找地址构造地址信息
        add = Address.objects.filter(id=address_id).first()
        addressSer = ShowAddressManageSer(add)
        address = addressSer.data
        print(address)
        addressStr = str(address['province']) + ' ' + str(address['city']) + ' ' + str(address['area']) + ' ' + str(address[
            'address']) + ' ' + str(address['receive']) + ' ' + str(address['mobile'])
        datam = {'order_no':order_no,'user':userid,'address':addressStr,'total_amount':total_amount,'pay_method':pay_method}

        # 创建事务结点
        sid = transaction.savepoint()
        try:#调用序列化器添加订单
            ser = OrderInfoSer(data=datam)
            if ser.is_valid():
                ser.save()
                # 生成订单详情)
                for i in careser.data:
                    detaildata = {'order': order_no, 'goods': i['goods']['id'], 'goodsname': i['goods']['name'],
                                  'images':
                                      i['goods']['pic'], 'count': i['number'], 'price': float(i['goods']['price']),
                                  'user': userid}
                    # 调用序列化器添加订单详情
                    dser = OrderDetailSer(data=detaildata)
                    if dser.is_valid():
                        dser.save()
            # 生成订单详情购物车删除已经生成订单记录
            Cart.objects.filter(user_id=userid, is_checked=True).delete()
            # 提交事务
            transaction.savepoint_commit(sid)
            # 返回结果
            return Response({"code": 200, 'order_no': order_no, 'total_amount': total_amount})
        except:
            # 事务回滚
            transaction.savepoint_rollback(sid) 
            return Response({'code':20010})













